/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.senai.view;

import br.com.senai.config.Config;
import br.com.senai.dao.EscolaDAO;
import br.com.senai.entities.Escola;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;

/**
 *
 * @author Hugo
 */
public class Opcoes extends javax.swing.JFrame {

    /**
     * Creates new form Opcoes
     */
    public Opcoes() {
        initComponents();
        super.setTitle(Config.NOME_SISTEMA+super.getTitle());
        this.setIconImage(Config.LOGO_SISTEMA);
        this.getContentPane().setBackground(Config.corFundo);
        carregarInformacoes();
    }

    public void atualizarPainelEscolas() {
        GridLayout layout = new GridLayout(1, 4, 2, 3);
        painelEscolas.removeAll();

        painelEscolas.setLayout(layout);

        for (final Escola escola : new EscolaDAO().listar()) {
            painelEscolas.add(new JCheckBox(new AbstractAction(escola.getNome(), null) {

                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println(escola.getNome());
                }
            }) {

                @Override
                public void setLabel(String label) {
                    super.setLabel(escola.getNome()); //To change body of generated methods, choose Tools | Templates.
                }

                @Override
                public void setName(String name) {
                    super.setName(escola.getNome()); //To change body of generated methods, choose Tools | Templates.
                }
            });
        }

        painelEscolas.repaint();

    }

    public void carregarInformacoes() {
        GridLayout layout = new GridLayout( (int) (new EscolaDAO().listar().size()/3), 3, 2, 3);
        painelEscolas.removeAll();

        painelEscolas.setLayout(layout);

        for (final Escola escola : new EscolaDAO().listar()) {
            painelEscolas.add(new CheckBox(null, escola.getNome(), false));
        }
           List<String> linhas;
            try {
                linhas = Files.readAllLines(Paths.get("escolas.txt"), StandardCharsets.UTF_8);
            } catch (IOException ex) {
                linhas = null;
            }
            for (String linha : linhas) {
                String[] split = linha.split(";");
                
                for (String palavra : split) {
                    
                   for(Component component:painelEscolas.getComponents()){
                       if(component instanceof CheckBox){
                           if(palavra.equalsIgnoreCase(((CheckBox)component).getName())){
                               ((CheckBox)component).setSelected(true);
                           }
                       }
                   }

                }
        }

        painelEscolas.repaint();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        painelEscolas = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Sistema de Pães - Configurações");

        jButton1.setText("Salvar");
        jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Configurar escolas permitidas:");

        javax.swing.GroupLayout painelEscolasLayout = new javax.swing.GroupLayout(painelEscolas);
        painelEscolas.setLayout(painelEscolasLayout);
        painelEscolasLayout.setHorizontalGroup(
            painelEscolasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 398, Short.MAX_VALUE)
        );
        painelEscolasLayout.setVerticalGroup(
            painelEscolasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 48, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(painelEscolas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jButton1))
                .addContainerGap(22, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(painelEscolas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(71, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Escolas permitidas", jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1))
        );

        setSize(new java.awt.Dimension(471, 261));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String texto = "";

        try {

            for (Component c : painelEscolas.getComponents()) {

                if (c instanceof JCheckBox) {
                    if (((JCheckBox) c).isSelected()) {
                        texto += ((JCheckBox) c).getText() + ";";
                    }
                }

            }

            Files.write(Paths.get("escolas.txt"), (texto).getBytes("utf-8"), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
            JOptionPane.showMessageDialog(null, "Salvo com sucesso!", "Resposta", JOptionPane.INFORMATION_MESSAGE);
            
        } catch (IOException ex) {
            Logger.getLogger(Opcoes.class.getName()).log(Level.SEVERE, null, ex);
        }


    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Opcoes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Opcoes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Opcoes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Opcoes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Opcoes().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JPanel painelEscolas;
    // End of variables declaration//GEN-END:variables
}
